# -*- coding: utf-8 -*-
# author: sixmillions
# date: 2022/04/18

import os
import time

from PIL import Image
from selenium import webdriver
from selenium.webdriver.common.keys import Keys

from util_demo.p003_baidu_ocr import baidu_ocr
# 常量定义
# DRIVER_PATH = r'D:\OpenSources\chromedriver_win32\chromedriver.exe'
from util_demo.p004_send_mail import send_mail

DRIVER_PATH = r'D:\OpenSources\edgedriver_win64\msedgedriver.exe'
WEB_URL = os.environ.get('MRJK_URL')
ACCOUNT = os.environ.get('ACCOUNT')
COMPANY = os.environ.get('COMPANY')


def open_browser():
    # browser = webdriver.Chrome(executable_path=DRIVER_PATH)
    browser = webdriver.Edge(executable_path=DRIVER_PATH)
    browser.get(WEB_URL)
    time.sleep(1)
    return browser


def write_info(browser):
    # 点击供应商
    browser.find_element_by_xpath("//*[contains(text(),'供应商')]").click()  # 部分文字
    # 输入账号和公司
    browser.find_element_by_xpath('//*[@id="app"]/div/div/div[2]/div[2]/div[2]/div/div[1]/div[2]/div/input') \
        .send_keys(ACCOUNT)
    browser.find_element_by_xpath('//*[@id="app"]/div/div/div[2]/div[2]/div[2]/div/div[2]/div[2]/div/input').click()
    browser \
        .find_element_by_xpath(
        '//*[@id="app"]/div/div/div[2]/div[2]/div[2]/div/div[4]/div[1]/div[1]/div/div[2]/div/input') \
        .send_keys(COMPANY[:6])
    time.sleep(1)
    browser.find_element_by_xpath("//*[contains(text(),'搜索')]").click()
    time.sleep(3)
    browser.find_element_by_xpath('//*[@id="app"]/div/div/div[2]/div[2]/div[2]/div/div[4]/div[2]/div[1]/div').click()
    time.sleep(1)


# 识别验证码并输入
def access_ocr(browser):
    img_ele = browser.find_element_by_xpath('//*[@id="app"]/div/div/div[3]/div[2]/div/div/img')
    time.sleep(3)
    browser.get_screenshot_as_file('./screenshot.png')
    left = int(img_ele.location['x'])
    top = int(img_ele.location['y'])
    right = int(img_ele.location['x'] + img_ele.size['width'])
    bottom = int(img_ele.location['y'] + img_ele.size['height'])
    im = Image.open('./screenshot.png')
    im = im.crop((left, top, right, bottom))
    im.save('./access.png')

    # img_data = base64.b64decode(img_ele.screenshot_as_base64)
    # img_name = os.path.join('./', 'access.png')
    # with open(img_name, 'wb')as f:
    #     f.write(img_data)

    # img_data = img_ele.screenshot_as_png
    # with open(r'./access.png', 'wb') as f:
    #     f.write(img_data)
    access_code = baidu_ocr(r'./access.png')

    print('识别结果：', access_code)
    # 清空（clear失败：https://blog.csdn.net/sun_977759/article/details/108731881）
    ele = browser.find_element_by_xpath('//*[@id="app"]/div/div/div[3]/div[2]/div/input')
    ele.send_keys(Keys.CONTROL, 'a')
    ele.send_keys(access_code)


def do_login(browser):
    # 进入答题
    browser.find_element_by_xpath('//*[@id="app"]/div/div/div[5]/div/button').click()
    time.sleep(3)
    list = browser.find_elements_by_xpath("//*[contains(text(),'SGM人人健康每日申报系统')]")
    print("跳转判断：", len(list), list)
    return len(list)


def do_report(browser):
    # 做题
    # 7题
    browser.find_element_by_xpath("//*[contains(text(),'不属于政府')]").click()
    # 31题
    browser.find_element_by_xpath("//*[contains(text(),'未居住在上海')]").click()
    # 提交
    browser.find_element_by_xpath('//*[@id="app"]/div/div/button').click()
    time.sleep(2)
    browser.find_element_by_xpath("/html/body/div[4]/div[3]/button[2]").click()
    # 截图
    # browser.get_screenshot_as_file(r"./mrjk.png")
    browser.get_screenshot_as_file(r"/opt/packages/mrjk.png")


# 查询结果
# browser.find_element_by_xpath('//*[@id="app"]/div/div/div[7]/div/button').click()


if __name__ == '__main__':
    print("=============start=============")
    browser = open_browser()
    write_info(browser)
    access_ocr(browser)
    num = do_login(browser)
    for i in range(5):
        if num == 1:
            do_report(browser)
            break
        else:
            print("验证码错误，尝试第：", i + 1, '次')
            access_ocr(browser)
            num = do_login(browser)

    time.sleep(10)
    # 关闭浏览器
    browser.close()
    # 发送邮件
    print("发送邮件")
    subject = time.strftime('%Y-%m-%d', time.localtime()) + ' 自动执行结果'
    send_mail(subject)
    print("==============end==============")
